package toOffer;

/**
 * <h3>leetcode</h3>
 *
 * @author BigFaceCat
 * @date 2024/1/26 14:51
 * @description <p>反转链表</p>
 */

import java.util.Stack;

/**
 * 题目：定义一个函数，输入一个链表的头节点，反转该链表并输出反
 * 转后链表的头节点。例如，把图 4.8（a）中的链表反转之后得到的链表如
 * 图 4.8（b）所示。
 */
public class toOffer4_4_24 {
    public static void main(String[] args) {
        // 1 2 3 4 5
        ListNode node4 = new ListNode(5);
        ListNode node3 = new ListNode(4, node4);
        ListNode node2 = new ListNode(3, node3);
        ListNode node1 = new ListNode(2, node2);
        ListNode head = new ListNode(1, node1);

        System.out.println(reverseList(head).getVal());
    }

    /**
     * 方法二：栈
     * @param head
     * @return
     */
    public static ListNode reverseList(ListNode head) {
        //判空
        if (head == null) {
            return null;
        }
        Stack<ListNode> stack = new Stack<>();

        //把节点压入栈
        while (head != null){
            stack.push(head);
            head = head.next;
        }
        ListNode tempNode = stack.pop();
        ListNode newHead = tempNode;
        //提取节点
        while (!stack.isEmpty()){
            tempNode.next = stack.pop();
            tempNode = tempNode.next;
        }
        //需要赋空值，不然next指向的是前面弹出栈的节点，生成的链表会形成回路
        tempNode.next = null;
        return newHead;
    }

    /**
     * 方法一：三指针
     * @param head
     * @return
     */
    public static ListNode reverseList1(ListNode head) {
        //判空
        if (head == null) {
            return null;
        }

        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public int getVal(){
            return this.val;
        }

    }
}
